package com.winit.mq.task;

import com.winit.util.SysInfoTable;
import com.winit.websocket.util.SendMessageUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.TextMessage;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TailLogTask implements Runnable{

	private static final Logger logger = LoggerFactory.getLogger(TailLogTask.class);
	
	private boolean exit = false;
	private String[] params;
	private String tokenId;
	private String threadId;
	private Process process = null;
	
	public TailLogTask(String[] params,String tokenId,String threadId){
		this.params = params;
		this.tokenId = tokenId;
		this.threadId = threadId;
	}
	
	public void shutThread(){
		logger.info("关闭tail日志线程；exit=true");
		this.exit = true;
		if(process != null){
			process.destroy();
		}
	}
	
	public void run(){
		logger.info("启动线程查询日志，threadId="+threadId);
		try {
			process = Runtime.getRuntime().exec(params);
			Thread.sleep(3000);
			BufferedInputStream in = new BufferedInputStream(process.getInputStream());  
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String line;
			while ((!exit) && ((line=br.readLine()) != null)) {
				logger.info("查询日志，line＝"+line);
				if(("build success").equals(line) || ("maven mq success").equals(line) ||
						("release success").equals(line) || ("release error").equals(line)){
					SendMessageUtil.sendMessageToUser(tokenId, new TextMessage(line),threadId);
					break;
				}

				Pattern pattern = Pattern.compile("^[0-9]*/[0-9]* KB.*");
				Matcher matcher = pattern.matcher(line);
				boolean flag = matcher.matches();
				if( flag || StringUtils.isEmpty(line)){
					continue;
				}

				SendMessageUtil.sendMessageToUser(tokenId, new TextMessage(line),threadId);
			}
			br.close();
			in.close();
		} catch (Exception e) {
			logger.info("查询日志异常,e:"+e);
		}
		if(!StringUtils.isEmpty(threadId)){
			SysInfoTable.threadMap.remove(threadId);
		}
		logger.info("查询日志线程关闭，threadId="+threadId);
		
	}
	
}
